package com.hz.controller;

import com.hz.pojo.Category;
import com.hz.pojo.Result;
import com.hz.service.CategoryService;
import com.hz.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("")
    public Result addCategory(@RequestBody @Validated(Category.Add.class) Category category){
        // 查询类别名称是否已经存在
        Category c = categoryService.findByName(category.getCategoryName());
        if (c!=null){
            return Result.error("文章类别已经存在，请勿重复添加");
        }
        int rs = categoryService.addCategory(category);
        if (rs==1){
            return Result.success("新增文章类别成功！");
        }
        return Result.error("操作失败");
    }

    @GetMapping("")
    public Result<List<Category>> getCategory(){
        // 获取当前用户的id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        List<Category> categories = categoryService.listCategory(id);
        return Result.success(categories);
    }

    @GetMapping("/detail")
    public Result<Category> getDetail(Integer id){
        return Result.success(categoryService.findCategory(id));
    }

    @PutMapping("")
    public Result updateCategory(@RequestBody @Validated(Category.Update.class) Category category){

        Integer id = category.getId();
        String categoryName = category.getCategoryName();
        String categoryAlias = category.getCategoryAlias();

        int rs = categoryService.updateCategory(id,categoryName,categoryAlias);

        if (rs==1){
            return Result.success("更新成功");
        }
        return Result.error("更新失败@！");
    }

    @DeleteMapping("")
    public Result deleteCategory(Integer id){
        int rs  = categoryService.deleteByID(id);
        if (rs==1){
            return Result.success("删除成功");
        }
        return Result.error("操作失败！");
    }


}
